package com.mdlaser.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author 朱艺超
 * @version 2022.0901
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {

  static ApplicationContext applicationContext=null;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringBeanUtil.applicationContext =applicationContext;
  }

  public static <T> T getBean(Class<T> requiredType) throws BeansException{
    return applicationContext.getBean(requiredType);
  }


  public static Object getBean(String beanName) {
    try{
      return applicationContext != null ? applicationContext.getBean(beanName) : null;
    }
    catch (Exception ex){
      return null;
    }
  }
}
